﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using ImportFromSql.Properties;
using Microsoft.SharePoint;

namespace ImportFromSql
{
    class Program
    {
        static void Main(string[] args)
        {
            if (!IsWebAndListExist(Settings.Default.SharepointUrl, Settings.Default.SharepointListName))
                return;   
            ProcessSql();
        }
        private static void ProcessSql()
        {
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection(Settings.Default.ConnectionString);
            con.Open();
            SqlCommand command = new SqlCommand(Settings.Default.Query, con);
            SqlDataAdapter sa = new SqlDataAdapter(command);
            try
            {
                sa.Fill(dt);
            }
            catch (SqlException) 
            {
                Console.WriteLine("Ошибка конфигурирования файла настроек.");
                return;
            }
            con.Close();
            Dictionary<string, string> fieldsMappingDictionary = new Dictionary<string, string>();
            foreach (string item in Settings.Default.MappingDictionary)
            {
                string[] h = item.Split(new char[] { '=' });
                fieldsMappingDictionary.Add(h[0], h[1]);
            }
            MoveData.MoveFromSqlToSPList(dt,
                    Settings.Default.SharepointUrl,
                    Settings.Default.SharepointListName,
                    fieldsMappingDictionary,
                    Settings.Default.SharepointKeyField,
                    Settings.Default.SqlKeyField);

        }
        /// <summary>
        /// Проверяем наличие узла и списка.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="listname"></param>
        /// <returns></returns>
        private static bool IsWebAndListExist(string path, string listname)
        {
            using (SPSite site = new SPSite(path))
            using (SPWeb web = site.OpenWeb())
            {
                if (web == null)
                {
                    Console.WriteLine("Отсутствует узел SharePoint. Проверьте файл настроек.");
                    return false;
                }
                foreach (SPList item in web.Lists)
                    if (item.Title.Equals(listname))
                        return true;
                return false;
            }
        }
    }
}
